package com.foreknow.controller;

import com.foreknow.bean.Admin;
import com.foreknow.service.AdminService;
import com.foreknow.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Servlet: 服务器端的应用程序。
 * 作用：处理客户端发送的请求
 * 编写Servlet的流程
 * 1. 继承HttpServlet
 * 2. 重写doGet/doPost方法
 *      如果客户端向服务器端发送的是get请求，就会调用doGet方法
 *      如果客户端向服务器端发送的是post请求，就会调用doPost方法
 *   HttpServletRequest表示请求对象(接口)
 *   HttpServletResponse表示响应对象(接口)
 *
 * Servlet的生命周期
 * 1. init()初始化的方法，只调用一次
 * 2. service()方法,对于我们来说是透明的,它会根据用户发送请求的方式来决定调用doGet/doPost
 * 3. destroy() 销毁方法，只调用一次。
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器向客户端响应的内容的类型
        //resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端发送请求的字符编码集
        //req.setCharacterEncoding("utf-8");
        //通过getWriter方法获取PrintWriter输出流对象，主要用于在网页上输出结果
        PrintWriter out = resp.getWriter();
        //获取HttpSession对象
        HttpSession session = req.getSession();
        //获取用户名和密码(请求参数) ?email=gibson@163.com&password=123456
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用Service中登录的方法
        AdminService service = new AdminServiceImpl();
        Admin admin = service.isValidate(username,password);
        if(admin!=null) {
            session.setAttribute("admin",admin);
            //out.println(admin.getUsername() + "---" + admin.getPassword());
            //转发资源
            //req.getRequestDispatcher("manager?q=list").forward(req,resp);
            resp.sendRedirect("manager?q=list");
        }else {
            out.println("no user......");
        }

    }
}
